import random
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect


from PIL import ImageDraw, Image, ImageFont



# Create your views here.
import io
from django.urls import reverse


def f_login_page(request):
    return render(request, 'app02_login/login.html')


def f_login(request):
    v_post_dict = request.POST
    v_user_name = v_post_dict.get('user_name', None)
    v_user_password = v_post_dict.get('user_password', None)
    v_identify_page = v_post_dict.get('identify_page', None)
    v_save_time = 1 * 24 * 60 * 60
    v_session_dict = request.session
    v_identify_service = v_session_dict.get('identify_service', None)
    if v_identify_page is not None and v_identify_service is not None and v_identify_page == v_identify_service:
        if v_user_name == 'jitx' and v_user_password == '123456':  # 登录成功
            # 把服务器端的验证码删除
            del v_session_dict['identify_service']

            # 把用户名保存到session
            v_session_dict['activeuser'] = v_user_name

            from django.http import HttpResponseRedirect
            v_response = HttpResponseRedirect('/app02/index_page/')
            v_cookie_dict = request.COOKIES
            if (v_save_time is not None):
                if v_user_name not in v_cookie_dict:  # 第一次登录   记住密码
                    #  把用户名和密码保存到cookie
                    v_response.set_cookie(v_user_name, v_user_password, max_age=v_save_time)
                else:  # 不是第一次登录，记住密码
                    v_response.set_cookie(v_user_name, v_user_password, max_age=v_save_time)
                    pass
                pass

            return v_response
        else:
            return redirect('/app02/login_page/')
    else:
        return redirect('/app02/login_page/')


def f_login_name_password(request):
    v_post_dict = request.POST
    v_user_name = v_post_dict.get('user_name', None)
    v_cookie_dict = request.COOKIES
    v_password = v_cookie_dict.get(v_user_name, None)
    if not v_password:
        v_password = ''
        pass
    v_result = {'password': v_password}
    return JsonResponse(v_result)


def f_index_page(request):
    return render(request, 'app02_login/index.html')


def f_index_top_page(request):
    return render(request, 'app02_login/top.html')


def f_index_left_page(request):
    return render(request, 'app02_login/left.html')


def f_index_right_pagee(request):
    return render(request, 'app02_login/right.html')


def f_identifycode(request):
    response = HttpResponse()

    '''
    生成验证码图片  开始
    '''

    # 1动态创建1张图片
    # 引入随机函数模块

    # 定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), random.randrange(20, 100))
    width = 100
    height = 50
    # 创建画面对象
    # from tkinter import Image
    im =Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str[random.randrange(0, len(str))]
    # 构造字体对象
    font = ImageFont.truetype(r'C:\Windows\Fonts\SIMSUN.TTC', 40)
    # 构造字体颜色
    fontcolor1 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor1)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor2)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor4)
    # 释放画笔
    del draw

    #  把验证码的内容保存到session
    v_session_dict = request.session
    v_session_dict['identify_service'] = rand_str
    print(rand_str)

    # 2把图片转换成字节流
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    '''
    生成验证码结束
    '''

    # 第一参数 验证码图片的读取流    验证码内容
    image_date_b = buf.getvalue()

    # 把图片里的内容返回给浏览器
    response.write(image_date_b)

    # 告诉浏览器返回的是图片
    response['content-type'] = 'image/png'
    # 服务器端禁用缓存
    response['Expires'] = 0
    response['Cache-Control'] = 'no-store, no-cache, must-revalidate'
    response['Pragma'] = 'no-cache'

    return response


#  实现注销
def f_logout(request):
    v_session_dict = request.session
    if 'activeuser' in v_session_dict:
        del v_session_dict['activeuser']
        pass
    return redirect(reverse('app02:index_page'))